package com.gzyj.jtt808.v2013.protocol;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.annotation.JSONField;

import com.gzyj.jtt808.utils.HexBytesUtil;
import com.gzyj.jtt808.utils.IntUtils;
import com.gzyj.jtt808.v2013.enums.BusinessDataType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.Data;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.gzyj.jtt808.v2013.Package;
import com.gzyj.jtt808.v2011.enums.TextFlag;

/**
 * 文本信息下发
 *
 * @author lhj
 */
@Data
public class JTT808_0x8300 extends Package implements Serializable {
    private List<TextFlag> TextFlag;//文本信息标志位含义见 表 27
    private String TextInfo;//文本信息 最长为 1024 字节，经GBK编码

    public JTT808_0x8300() {
        super(BusinessDataType.文本信息下发.getCode());
    }

    @JSONField(serialize = false)
    private Integer textFlagVal;

    @Override
    public void encodeImpl(ByteBuf buf) {


        if (CollectionUtil.isNotEmpty(this.TextFlag)) {
            int sum = 0;
            for (TextFlag flag : TextFlag) {
                sum += flag.getCode();
            }
            buf.writeByte(sum);
        } else {
            this.TextFlag = new ArrayList<>();
            String str = IntUtils.intToBinary(this.textFlagVal, 8);
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == '1') {
                    int res = new Double(Math.pow(2, (8 - i - 1))).intValue();
                    TextFlag.add(com.gzyj.jtt808.v2011.enums.TextFlag.find(res));
                }
            }
            buf.writeByte(this.textFlagVal);
        }

        buf.writeCharSequence(TextInfo, Charset.forName("GBK"));

    }

    @Override
    public JTT808_0x8300 decodeImpl(ByteBuf buf) {
        byte[] temp = HexBytesUtil.readByOffset(buf, 1);
        this.textFlagVal=Integer.parseInt(HexBytesUtil.bytesToHex(temp),16);
        this.TextFlag = new ArrayList<>();
        String str = IntUtils.intToBinary(textFlagVal, 8);

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '1') {
                int res = new Double(Math.pow(2, (8 - i - 1))).intValue();
                TextFlag.add(com.gzyj.jtt808.v2011.enums.TextFlag.find(res));
            }
        }

        String hex = ByteBufUtil.hexDump(buf);
        int len = (hex.length()) / 2;
        byte[] t = HexBytesUtil.readByOffset(buf, len);
        this.TextInfo = new String(t, Charset.forName("GBK"));


        return this;
    }
}
